<template>
    <el-card>
        <el-form :model="searchModel" ref="searchForm" label-width="80px" :inline="true" size="small">
            <el-form-item>
                <el-input v-model="searchModel.nickName" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item>
                <el-input v-model="searchModel.username" placeholder="请输入学号" />
            </el-form-item>
            <el-form-item>
                <el-select v-model="searchModel.classId" clearable placeholder="请选择班级">
                    <el-option v-for="item in classList" :key="item.id" :label="item.className" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button icon="el-icon-search" type="primary" @click="search(pageNo, pageSize)">查询
                </el-button>
                <el-button icon="el-icon-refresh-right" @click="resetValue()">重置</el-button>
                <el-button icon="el-icon-plus" size="small" type="success" @click="addStudent()"
                v-if="hasPermission('sys:user:add')">新增用户</el-button>
            </el-form-item>

        </el-form>
        <!-- 用户表单数据 -->
        <el-table :height="tableHeight" :data="userList" border stripe style="width: 100%; margin-bottom: 10px">
            <el-table-column type="index" width="50"></el-table-column>
            <template v-for="item in tableProp">
                <el-table-column :prop="item.prop" :label="item.label" :width="item.width" :formatter="item.formatter">

                </el-table-column>

            </template>

            <el-table-column align="center" v-if="hasPermission('sys:user:edit')" prop="enabled" label="账号状态" width="100px">
                <template slot-scope="{row}">
                    <el-button v-if="row.enabled" type="success" icon="el-icon-check" size="mini" circle></el-button>
                    <el-button v-else type="danger" icon="el-icon-close" size="mini" circle></el-button>
                </template>
            </el-table-column>

            <el-table-column align="center" v-if="hasPermission('sys:user:edit')" min-width="180" label="操作">
                <template slot-scope="scope">
                    <el-button icon="el-icon-edit" type="primary" size="mini" @click="updateUser(scope.row)"
                    v-if="hasPermission('sys:user:edit')">编辑</el-button>
                    <el-button icon="el-icon-delete" type="danger" size="mini" @click="deleteUser(scope.row)"
                    v-if="hasPermission('sys:user:delete')">删除
                    </el-button>
                    <el-button icon="el-icon-setting" type="primary" size="mini" @click="assignRole(scope.row)"
                    v-if="hasPermission('sys:user:assign')">分配角色
                    </el-button>
                    <el-button type="info" size="mini" @click="detailed(scope.row)"
                    v-if="hasPermission('sys:user:edit')">详细信息
                    </el-button>
                </template>
            </el-table-column>


        </el-table>
        <!-- 分页工具栏 -->
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="pageNo" :page-sizes="[10, 20, 30, 40, 50]" :page-size="10"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>

        <!-- 新增学生弹框 -->
        <system-dialog :title="userInfoDialog.title" :visible="userInfoDialog.visible" :height="userInfoDialog.height"
            :width="userInfoDialog.width" @onClose="onClose" @onConfirm="onConfirm">
            <div slot="content">
                <el-form :model="userInfo" ref="userInfoForm" :rules="rules" label-width="100px" :inline="true"
                    size="small">
                    <el-form-item label="姓名" prop="nickName"><el-input
                            v-model="userInfo.nickName"></el-input></el-form-item>
                    <el-form-item label="性别" prop="sex">
                        <el-select v-model="userInfo.sex" placeholder="性别">
                            <el-option label="男" value="男">男</el-option><el-option label="女" value="女">女</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="学号/工号" prop="username"><el-input
                            v-model="userInfo.username"></el-input></el-form-item>
                    <el-form-item label="密码" prop="password"><el-input v-model="userInfo.password"
                            show-password></el-input></el-form-item>
                    <el-form-item label="班级" prop="classId">
                        <el-select v-model="userInfo.classId" clearable placeholder="班级">
                            <el-option v-for="item in classList" :key="item.id" :label="item.className" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="学制" prop="academicYear">
                        <el-select v-model="userInfo.academicYear" placeholder="学制">
                            <el-option label="三年制" value="3">三年制</el-option><el-option label="四年制" value="4">四年制</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="学历" prop="culturalLevelId">
                        <el-select v-model="userInfo.culturalLevelId" placeholder="学历">
                            <el-option v-for="item in codeCulturalLevel" :key="item.id" :label="item.value"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="入学时间" prop="admissionYear">
                        <el-date-picker v-model="userInfo.admissionYear" type="date" placeholder="选择日期"
                            format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="身份证" prop="idCard"><el-input v-model="userInfo.idCard"></el-input></el-form-item>
                    <p></p>
                    <el-form-item label="照片">
                        <el-upload :show-file-list="false" :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload" class="avatar-uploader" :data="uploadHeader"
                            action="http://localhost:8888/api/oss/file/upload?module=photoId">
                            <img v-if="userInfo.photoId" :src="userInfo.photoId">
                            <i v-else class="el-icon-plus avatar-uploader-icon" />
                        </el-upload>
                    </el-form-item>
                </el-form>
            </div>
        </system-dialog>
        
        <!-- 分配角色窗口 -->
        <system-dialog :title="assignDialog.title" :height="assignDialog.height" :width="assignDialog.width"
            :visible="assignDialog.visible" @onClose="onAssignClose" @onConfirm="onAssignConfirm">
            <div slot="content">
                <!-- 分配角色数据列表 -->
                <el-table ref="assignRoleTable" :data="assignRoleList" border stripe :height="assignHeight"
                    style="width: 100%; margin-bottom: 10px" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column prop="roleCode" label="角色编码" />
                    <el-table-column prop="roleName" label="角色名称" />
                    <el-table-column prop="roleDesc" label="角色描述" />
                </el-table>
                <!-- 分页工具栏 -->
                <el-pagination @size-change="assignSizeChange" @current-change="assignCurrentChange"
                    :current-page.sync="roleVo.pageNo" :page-sizes="[10, 20, 30, 40, 50]" :page-size="roleVo.pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="roleVo.total" background>
                </el-pagination>
            </div>
        </system-dialog>
        <!-- 用户详情 -->
        <el-drawer
            title="详细信息"
            :visible.sync="drawer"
            :with-header="false"
            size="50%">
            <div class="box">
                <el-form :model="user" ref="userForm" label-width="80px" :inline="true" >
                <el-form-item label="照片">
                    <el-image
                        style="width: 200px; height: 200px"
                        :src="user.photoId"
                       ></el-image>
                    </el-form-item>
                <el-form-item label="姓名" prop="nickName">
                    <el-input v-model="user.nickName" disabled></el-input>
                </el-form-item>
                <el-form-item label="学号" prop="username">
                    <el-input v-model="user.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="身份证" prop="idCard">
                    <el-input v-model="user.idCard" disabled></el-input>
                </el-form-item>
                <el-form-item label="出生日期" prop="dateOfBirth">
                    <el-date-picker v-model="user.dateOfBirth" type="date" disabled placeholder="选择日期" format="yyyy 年 MM 月 dd 日"
                        value-format="yyyy-MM-dd" style="width:190px">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="手机号" prop="telephone">
                    <el-input v-model="user.telephone" disabled></el-input>
                </el-form-item>
                <el-form-item label="班级" prop="classId">
                    <el-input v-model="classRoom" disabled></el-input>
                </el-form-item>
                <el-form-item label="学制" prop="academicYear">
                    <el-input v-model="user.academicYear" disabled></el-input>
                </el-form-item>
                <el-form-item label="入学时间" prop="admissionYear">
                    <el-date-picker v-model="user.admissionYear" type="date" placeholder="选择日期"
                        format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" disabled style="width:190px">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="民族" prop="nationalityId">
                    <el-select v-model="user.nationalityId" placeholder="民族" style="width:190px" disabled>
                        <el-option v-for="item in nationalityList" :key="item.id" :label="item.value"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="政治面貌" prop="politicalStatusId">
                    <el-select v-model="user.politicalStatusId" placeholder="政治面貌" style="width:190px" disabled>
                        <el-option v-for="item in politicalStatusList" :key="item.id" :label="item.value"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="user.sex" placeholder="性别" disabled style="width:190px">
                        <el-option v-for="item in sexProp" :key="item.id" :label="item.value"
                            :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="user.email" disabled></el-input>
                </el-form-item>
            </el-form>
            </div>
            </el-drawer>
    </el-card>
</template>

<script>
import userApi from '@/api/user'
import classApi from '@/api/class'
import SystemDialog from '@/components/system/SystemDialog.vue'
import common from '@/api/common'
import { getToken } from '@/utils/auth'
import { userInfo } from 'os'
import commonApi from "@/api/common"

export default {
    name: 'userList',
    components: {
        SystemDialog
    },
    data() {
        return {
            drawer:false,
            //分配角色窗口属性
            assignDialog: {
                title: "",
                visible: false,
                width: 800,
                height: 410,
            },
            //角色对象
            roleVo: {
                pageNo: 1,
                pageSize: 10,
                userId: "",
                total: 0,
            },
            assignRoleList: [], //角色列表
            assignHeight: 0, //分配角色表格高度
            selectedIds: [], //被选中的角色id
            selectedUserId: "", //被分配角色的用户ID
            //查询条件对象
            searchModel: {
                nickName: "",
                username: "",
                classId: "",
                pageNo: 1,
                pageSize: 10,
            },
            userList: [], //用户列表
            classList: [],//班级列表
            codeCulturalLevel: [],//学历表
            tableProp: [
                { prop: 'nickName', label: '姓名' },
                { prop: 'username', label: '学号' },
                {
                    prop: 'classId',
                    label: '班级',
                    formatter: value => {
                        const findClass = this.classList.find(classr => classr.id === value.classId)
                        return findClass !== undefined ? findClass.className : '-'
                    }
                }, { prop: 'sex', label: '性别', width: '80px' },
                { prop: 'telephone', label: '手机号' }
            ],
            userInfo: {
                id: null,
                nickName: null,
                username: null,
                password: null,
                classId: null,
                academicYear: null,
                culturalLevelId: null,
                admissionYear: null,
                sex: null,
                photoId: '',
                idCard: null,
            },
            user: {
                id: null,
                nickName: null,
                username: null,
                password: null,
                classId: null,
                academicYear: null,
                culturalLevelId: null,
                admissionYear: null,
                sex: null,
                photoId: '',
                idCard: null,
                dateOfBirth:null,
                telephone:null,
                nationalityId:null,
                politicalStatusId:null,
                email:null,
            },
            userInfoDialog: {
                title: '',
                visible: false,
                height: 470,
                width: 700,
            },
            uploadHeader: { "token": getToken() },
            rules: {
                nickName: [{ required: true, trigger: "blur", message: "请输入姓名" }],
                sex: [{ required: true, trigger: "change", message: "请选择性别" }],
                username: [{ required: true, trigger: "blur", message: "请输入学号" }],
                password: [{ required: true, trigger: "blur", message: "请输入密码" }],
                idCard: [{ required: true, trigger: "blur", message: "请输入身份证号" }],
            },
            tableHeight: 550, //表格高度
            pageNo: 1, //当前页码
            pageSize: 10, //每页显示数量
            total: 0, //总数量
            nationalityList: [],
            politicalStatusList: [],
            culturalLevelList: [],
            classRoom: '',
            sexProp: [
                { id: 1, value: '男', },
                { id: 2, value: '女', },
            ],
            cule: '',
        }
    },
    methods: {
        async getUserList() {
            let params = { pageNo: this.pageNo, pageSize: this.pageSize }
            let res = await userApi.getUserList(params)
            if (res.success) {
                this.userList = res.data.records
                this.total = res.data.total
            }
        },
        async getCodeCulturalLevel() {
            let res = await common.getCodeCulturalLevel()
            if (res.success) {
                this.codeCulturalLevel = res.data
            }
        },
        // 查询用户信息
        async search(pageNo = 1, pageSize = 10) {
            this.searchModel.pageNo = pageNo;
            this.searchModel.pageSize = pageSize;
            let res = await userApi.getUserList(this.searchModel);
            if (res.success) {
                this.userList = res.data.records
                this.total = res.data.total
            }
        },
        // 获取班级信息
        async getClassList() {
            let res = await classApi.getClassList(null)
            if (res.success) {
                this.classList = res.data.records
            }
        },
        //重置按钮
        resetValue() {
            this.searchModel = {}
            this.getUserList()
        },
        // 添加学生
        addStudent() {
            this.$resetForm('userInfoForm', this.userInfo)
            this.userInfoDialog.title = '添加用户'
            this.userInfoDialog.visible = true
        },
        onClose() {
            this.userInfoDialog.visible = false
        },
        onConfirm() {
            this.$refs.userInfoForm.validate(async (valid) => {
                if (valid) {
                    let res = null
                    if (this.userInfo.id === '') {
                        res = await userApi.addUser(this.userInfo)
                    } else {
                        res = await userApi.updateUser(this.userInfo)
                    }
                    if (res.success) {
                        this.$message.success(res.message)
                        this.search(this.pageNo, this.pageSize)
                        this.userInfoDialog.visible = false
                    } else {
                        this.$message.error("请检查信息是否填写正确")
                    }
                }
            })
        },
        // 上传照片成功回调
        handleAvatarSuccess(res, file) {
            this.userInfo.photoId = res.data
            console.log(res)
            this.$forceUpdate()
        },
        // 上传校验
        beforeAvatarUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!')
            }
            return isLt2M
        },
        updateUser(row) {
            this.userInfoDialog.title = '修改用户信息'
            this.userInfoDialog.visible = true
            this.$objCopy(row, this.userInfo)
        },
        async deleteUser(row) {
            let confirm = await this.$myconfirm("确定删除吗？")
            if (confirm) {
                let res = await userApi.deleteUserById({ id: row.id })
                if (res.success) {
                    this.search(this.pageNo, this.pageSize)
                    return this.$message.success(res.message)
                } else
                    return this.$message.error(res.message)
            }
        },
        detailed(row){
            this.drawer = true
            this.$objCopy(row, this.user)
            const classRoom = this.classList.find(classRoom => classRoom.id === this.user.classId)
            this.classRoom = classRoom.className
        },
        // 页数发生变化
        handleSizeChange(size) {
            this.pageSize = size
            this.search(this.pageNo, size)
        },
        // 页码发生变化
        handleCurrentChange(page) {
            this.pageNo = page
            this.search(page, this.pageSize)
        },
        /**
* 打开分配角色
*/
        async assignRole(row) {
            //防止回显出现问题
            this.selectedIds = [];
            this.selectedUserId = "";
            //被分配用户的id
            this.selectedUserId = row.id;
            //显示窗口
            this.assignDialog.visible = true;
            //设置标题
            this.assignDialog.title = `给【${row.nickName}】分配角色`;
            //查询当前登录用户的所有角色信息
            await this.getAssignRoleList();
            //获取当前被分配用户的ID
            let params = { userId: row.id, }
            //发送根据用户ID查询角色列表的请求
            console.log(params)
            let res = await userApi.getRoleByUserId(params);
            //如果存在数据
            if (res.success && res.data) {
                //将查询到的角色ID列表交给选中角色数组
                this.selectedIds = res.data;
                //循环遍历
                this.selectedIds.forEach((key) => {
                    this.assignRoleList.forEach((item) => {
                        if (item.id === key) {
                            this.$refs.assignRoleTable.toggleRowSelection(item, true);
                        }
                    });
                });
            }
        },
        /**
* 查询当前登录用户的所有角色信息
*/
        async getAssignRoleList(pageNo = 1, pageSize = 10) {
            //给用户ID赋值
            this.roleVo.userId = this.$store.getters.userId;
            this.roleVo.pageNo = pageNo;
            this.roleVo.pageSize = pageSize;
            //发送查询请求
            let res = await userApi.getRoleList(this.roleVo);
            //判断是否成功
            if (res.success) {
                //角色列表赋值
                this.assignRoleList = res.data.records;
                //角色总数量赋值
                this.roleVo.total = res.data.total;
            }
        },
        /**
* 分配角色取消事件
*/
        onAssignClose() {
            //隐藏窗口
            this.assignDialog.visible = false;
        },
        /**
        * 分配角色确认事件
        */
        async onAssignConfirm() {
            // 判断角色是否被选中
            if(this.selectedIds.length === 0){
                return this.$message.warning("请选择要分配的角色")
            }
            let params = {
                userId : this.selectedUserId,
                roleIds : this.selectedIds
            }
            let res = await userApi.assignRoleSave(params)
            if(res.success){
                this.$message.success(res.message)
                //隐藏窗口
                this.assignDialog.visible = false;
            }else{ this.$message.error(res.message) }
            
        },
        /**
        * 当每页数量发生变化时触发该事件
        */
        assignSizeChange(size) {
            this.roleVo.pageSize = size; //将每页显示的数量交给成员变量
            this.getAssignRoleList(this.roleVo.pageNo, size);
        },
        assignCurrentChange(page) {
            this.roleVo.pageNo = page;
            //调用查询方法
            this.getAssignRoleList(page, this.roleVo.pageSize);
        },
        /**
        * 当点击多选框时触发该事件
        */
        handleSelectionChange(rows) {
            let roleIds = [];
            //循环遍历选中的角色ID
            for (let i = 0; i < rows.length; i++) {
                //将当前选中的角色ID放到数组中
                roleIds.push(rows[i].id);
            }
            //将选中的角色ID交给成员变量
            this.selectedIds = roleIds;
            // this.selectedIds = rows.map(item => item.id);//等同于上述代码
        },
        async init(){
            let res = await commonApi.getNationality()
            if(res.success){
                this.nationalityList = res.data
                console.log(res)
            }
            let res2 = await commonApi.getPoliticalStatus()
            if(res2.success){
                this.politicalStatusList = res2.data
            }
        }
    },
    created() {
        this.getUserList();
        this.getClassList();
        this.getCodeCulturalLevel();
        this.init()
    },
    mounted() {
        this.$nextTick(() => {
            //内容高度
            this.containerHeight = window.innerHeight - 85
            //表格高度
            this.tableHeight = window.innerHeight - 220
            //角色表格高度
            this.assignHeight = window.innerHeight - 350;
        })
    },
}


</script>

<style lang="scss" scoped>
//用户头像
.avatar-uploader .el-upload {
    border: 1px dashed #afaeae !important;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar-uploader img {
    width: 178px;
    height: 178px;
    display: block;
}
.box{
    padding: 50px;
}
</style>